﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using YourFileWatcher.Models;

namespace YourFileWatcher
{
    /// <summary>
    /// LoginWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        public LoginWindow()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 主窗体，用于数据交互
        /// </summary>
        public MainWindow MainWindow { get; set; }


        /// <summary>
        /// 验证输入的账号密码的合法性
        /// </summary>
        /// <param name="loginId">账号</param>
        /// <param name="password">密码</param>
        /// <returns>合法返回True</returns>
        private bool ValidateUserLoginInfoInternal(string loginId, string password)
        {
            return !String.IsNullOrWhiteSpace(loginId) && !String.IsNullOrWhiteSpace(password);
        }

        /// <summary>
        /// 尝试登陆
        /// </summary>
        private void TryLoginInternal()
        {
            string user = txtLoginUser.Text;
            string pwd = pwdPassword.Password;

            if (!ValidateUserLoginInfoInternal(user, pwd)) return;

            string filePath = String.Format(@"Content\{0}.db", user);
            UserInfo fUser = UserInfo.FromFile(filePath);
            if (fUser.Password == pwd)
            {
                //成功登陆
                MainWindow.LoginUser = fUser;
                this.DialogResult = true;
            }
        }


        private void btnSubmit(object sender, RoutedEventArgs e)
        {
            TryLoginInternal();
        }

        private void btnCancle(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void gridMain_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key==Key.Enter)
            {
                TryLoginInternal();
            }
        }
    }
}
